package cn.fsd.util;

import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class StoreroomRedisUtils {

    public StoreroomRedisUtils(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
        LettuceConnectionFactory redisConnectionFactory = (LettuceConnectionFactory) this.redisTemplate
                .getConnectionFactory();
        if (redisConnectionFactory == null) {
            return;
        }
        redisConnectionFactory.setDatabase(1);
        this.redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 属性设置后
        redisConnectionFactory.afterPropertiesSet();
        // 重置连接
        redisConnectionFactory.resetConnection();
    }


    final
    RedisTemplate<String,String> redisTemplate;

    public Boolean isListEmpty(String key){
        Long size = redisTemplate.opsForList().size(key);
        if(size==null)return true;
        return size==0;
    }
    public Long queueIn(String key, String value){

        return redisTemplate.opsForList().leftPush(key,value);
    }

    public String queueOut(String key){
        return redisTemplate.opsForList().rightPop(key);
    }

    public Object queueTop(String key){
        String order_id = redisTemplate.opsForList().rightPop(key);
        assert order_id != null;
        redisTemplate.opsForList().rightPush(key,order_id);
        return order_id;
    }
    public void delDB(){
        Set<String> keys = redisTemplate.keys("*");
        if(keys==null)return;
        redisTemplate.delete(keys);
    }


    public void listRemove(String key,String value){
        redisTemplate.opsForList().remove(key,0,value);
    }

    public void sSet(String key, String value) {
        redisTemplate.opsForSet().add(key, value);
    }

    public Long listLength(String key) {
        return redisTemplate.opsForList().size(key);
    }

    public Boolean isMember(String key, Object obj) {
        return redisTemplate.opsForSet().isMember(key, obj);
    }

    public void remove(String key, Object... values) {
        redisTemplate.opsForSet().remove(key, values);
    }

}
